import React, { PureComponent } from 'react'
import { Modal, Tree } from 'antd'
import PropTypes from 'prop-types'

// import Style from './setAuthModal.css'

const { TreeNode } = Tree
class setAuthModal extends PureComponent {
  static propTypes = {
    visible: PropTypes.bool,
    onCancel: PropTypes.func,
    tree: PropTypes.array,
    auth: PropTypes.array,
    onOk: PropTypes.func
  }

  constructor (props) {
    super(props)
    this.state = {
      expandedKeys: [],
      checked: []
    }
  }

  onExpand = expandedKeys => {
    this.setState({
      expandedKeys
    })
  }
  handleCheckAuth = (checkedKeys, info) => {
    this.setState({
      checked: checkedKeys.checked
    })
  }

  handleSubmit = () => {
    const { checked } = this.state
    const { onOk } = this.props
    if (checked && checked.length) {
      // TODO submit
      onOk(checked)
      this.handleClose()
    } else {
      Modal.confirm({
        title: '确认',
        content: '注意，未选择权限！',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          onOk(checked)
        }
      })
    }
  }
  handleClose = () => {
    const { onCancel } = this.props
    this.setState({
      checked: []
    })
    onCancel()
  }

  render () {
    const { expandedKeys, checked } = this.state
    const { visible, tree = [], auth = [] } = this.props
    const checkedKeys = checked.length ? checked : auth
    const loop = data =>
      data.map(item => {
        if (item.childLinkList && item.childLinkList.length) {
          return (
            <TreeNode key={item.menuId} title={item.menuName}>
              {loop(item.childLinkList)}
            </TreeNode>
          )
        }
        return <TreeNode key={item.menuId} title={item.menuName} />
      })
    return (
      <Modal
        title='权限配置'
        visible={visible}
        onCancel={this.handleClose}
        onOk={this.handleSubmit}
        bodyStyle={{ maxHeight: 520, overflow: 'auto' }}
      >
        <Tree
          checkable
          checkStrictly
          onExpand={this.onExpand}
          expandedKeys={expandedKeys}
          // defaultCheckedKeys={auth}
          checkedKeys={checkedKeys}
          onCheck={this.handleCheckAuth}
        >
          {loop(tree)}
        </Tree>
      </Modal>
    )
  }
}

export default setAuthModal
